package com.qd.system.importexcel.org;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cdqidi.dto.BatchResult;
import com.cdqidi.excel.domain.ExcelRowMsg;
import com.cdqidi.excel.domain.ImportErr;
import com.cdqidi.excel.util.ExcelUtil;
import com.cdqidi.exception.ApiException;
import com.cdqidi.exception.ExcelOperatorException;
import com.cdqidi.util.ValidatorUtil;
import com.cdqidi.valid.group.DefaultGroup;
import com.qd.common.sys.constant.Constants;
import com.qd.common.sys.domain.entity.org.OrgDTO;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.system.model.Org;
import com.qd.system.service.dict.MbUtil;
import com.qd.system.service.org.OrgService;
import com.qd.system.treecl.TreeClDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintViolationException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

/**
 * 组织机构,excel导入处理类
 *
 * @author sjk
 */
@Slf4j
public class OrgImportHandler {

    private final OrgService orgService;
    private final ValidatorUtil validatorUtil;
    private final List<ImportErr> errorList;
    private final LocalDateTime now = LocalDateTime.now();

    public OrgImportHandler(OrgService orgService, ValidatorUtil validatorUtil, List<ImportErr> errorList) {
        this.orgService = orgService;
        this.validatorUtil = validatorUtil;
        this.errorList = errorList;
    }

    /**
     * 处理具体导入
     *
     * @param rowList excel行数据集合，默认为1000行
     * @param results 异常信息存储
     */
    public void process(List<ExcelRowMsg<OrgDTO>> rowList, List<BatchResult> results) {
        final List<OrgDTO> orgList = rowList.stream().map(ExcelRowMsg::getRowData).collect(toList());
        final List<Org> existsOrgList = existsOrgList(orgList);
        final int size = rowList.size();
        try {
            for (ExcelRowMsg<OrgDTO> excelRowMsg : rowList) {
                final OrgDTO orgDto = excelRowMsg.getRowData();
                final ReadRowHolder readRowHolder = excelRowMsg.getReadRowHolder();
                final List<String> errors = buildImportDto(orgDto);
                if (!errors.isEmpty()) {
                    errorList.add(ExcelUtil.buildError(readRowHolder, errors));
                }
            }
            if (!errorList.isEmpty()) {
                throw new ExcelOperatorException(errorList);
            } else {
                final List<Org> addOrgList = new ArrayList<>(size);
                final List<Org> updateOrgList = new ArrayList<>(size);
                doProcessDictData(existsOrgList, orgList, addOrgList, updateOrgList);
                BatchResult.buildBatchResult(results, addOrgList.size(), updateOrgList.size());
                addOrgList.clear();
                updateOrgList.clear();
            }
        } finally {
            orgList.clear();
            existsOrgList.clear();
        }
    }

    /**
     * 保存数据
     *
     * @param existsOrgList 已经存在的数据
     * @param orgList       excel行数据集合
     * @param addOrgList    添加集合
     * @param updateOrgList 更新集合
     */
    private void doProcessDictData(List<Org> existsOrgList, List<OrgDTO> orgList, List<Org> addOrgList, List<Org> updateOrgList) {
        final int size = orgList.size();
        final List<TreeClDTO> addTreeClList = new ArrayList<>(size);
        final List<TreeClDTO> updateTreeClList = new ArrayList<>(size);
        final List<TreeClDTO> moveTreeClList = new ArrayList<>(size);

        orgList.forEach(orgDto -> {
            final Org org = orgService.dtoToModel(orgDto);
            orgService.clearCache(org);
            final TreeClDTO treeClDTO = orgService.buildTreeClDto();
            Org oldOrg = existsOrgList.stream().filter(orgModel -> {
                if (StringUtils.hasLength(org.getOrgId())) {
                    return orgModel.getOrgId().equals(orgDto.getOrgId());
                } else {
                    if (StringUtils.hasLength(org.getOrgName())) {
                        return orgModel.getOrgName().equals(orgDto.getOrgName());
                    }
                }
                return false;
            }).findFirst().orElse(null);
            if (null == oldOrg) {
                if(!StringUtils.hasLength(org.getOrgId())){
                    org.setOrgId(IdWorker.getIdStr());
                }
                org.setAddTime(now);
                org.setUpdateTime(null);
                addOrgList.add(org);
                addTreeClList.add(treeClDTO.setParam(org.getOrgId()));
            } else {
                org.setOrgId(oldOrg.getOrgId());
                org.setAddTime(null);
                org.setUpdateTime(now);
                updateOrgList.add(org);
                treeClDTO.setParam(org.getOrgId());
                if(StringUtils.hasLength(org.getParentId()) && StringUtils.hasLength(oldOrg.getParentId())){
                    if (org.getParentId().equals(oldOrg.getParentId())) {
                        updateTreeClList.add(treeClDTO);
                    } else {
                        moveTreeClList.add(treeClDTO);
                    }
                }else{
                    moveTreeClList.add(treeClDTO);
                }
            }
        });
        if (!addOrgList.isEmpty()) {
            orgService.saveBatch(addOrgList);
        }
        if (!updateOrgList.isEmpty()) {
            orgService.updateBatchById(updateOrgList);
        }
        if (!addTreeClList.isEmpty()) {
            orgService.getTreeClService().batchAdd(addTreeClList);
        }
        if (!updateTreeClList.isEmpty()) {
            orgService.getTreeClService().batchUpdate(updateTreeClList);
            updateTreeClList.clear();
        }
        if (!moveTreeClList.isEmpty()) {
            orgService.getTreeClService().batchMove(moveTreeClList);
            moveTreeClList.clear();
        }
    }

    /**
     * 根据主键查询存在的机构列表
     *
     * @param orgList excel行数据集合
     * @return 主键集合
     */
    private List<Org> existsOrgList(List<OrgDTO> orgList) {
        final List<String> ids = new ArrayList<>(orgList.size());
        final List<String> nameList = new ArrayList<>(orgList.size());
        for (OrgDTO orgDTO : orgList) {
            if (StringUtils.hasLength(orgDTO.getOrgId())) {
                ids.add(orgDTO.getOrgId());
            } else {
                if (StringUtils.hasLength(orgDTO.getOrgName())) {
                    nameList.add(orgDTO.getOrgName());
                }
            }
        }
        List<Org> existsIds = new ArrayList<>(orgList.size());
        if (!ids.isEmpty()) {
            List<Org> dbOrgList = orgService.listByIds(ids);
            if (!dbOrgList.isEmpty()) {
                existsIds.addAll(dbOrgList);
                dbOrgList.clear();
            }
            ids.clear();
        }
        if (!nameList.isEmpty()) {
            List<Org> dbOrgList = orgService.listByOrgNames(nameList);
            if (!dbOrgList.isEmpty()) {
                Map<OrgDTO, Integer> countMap = CollUtil.countMap(orgList);
                for (OrgDTO orgDTO : countMap.keySet()) {
                    Integer count = countMap.get(orgDTO);
                    if (count > 1) {
                        throw new ApiException("机构名字[" + orgDTO.getOrgName() + "]有重复值，请指定机构ID");
                    }
                }
                existsIds.addAll(dbOrgList);
                dbOrgList.clear();
            }
        }
        return existsIds;
    }

    /**
     * 导入验证
     *
     * @param orgDto 单个excel行数据
     * @return 异常信息
     */
    private List<String> buildImportDto(OrgDTO orgDto) {
        final List<String> errors = new ArrayList<>();
        //验证信息，自己编写
        final Integer orgStatus = MbUtil.isStatusValidate(errors, orgDto.getOrgStatusDisplay());
        if (null != orgStatus) {
            orgDto.setOrgStatus(orgStatus);
        }
        if (!StringUtils.hasLength(orgDto.getParentId())) {
            if (StringUtils.hasLength(orgDto.getOrgId())) {
                if (orgDto.getOrgId().equals(Constants.DEFAULT_TREE_PARENT_ID)) {
                    orgDto.setParentId(null);
                } else {
                    orgDto.setParentId(SecurityUtils.getLoginUser().getCurrentOrgId());
                }
            }else{
                orgDto.setParentId(SecurityUtils.getLoginUser().getCurrentOrgId());
            }
        }
        importValidate(orgDto, errors);
        return errors;
    }

    /**
     * 导入实体验证
     *
     * @param orgDto 单个excel行数据
     * @param errors 异常信息存储
     */
    private void importValidate(OrgDTO orgDto, List<String> errors) {
        if (errors.isEmpty()) {
            try {
                validatorUtil.checkValid(orgDto, DefaultGroup.class);
            } catch (ConstraintViolationException e) {
                errors.addAll(validatorUtil.getValidationError(e));
            }
        }
    }
}